import { useAntdTable } from 'ahooks';
import { Form, Input, Space, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useRef } from 'react';

import rolesApi from '@/api/rolesApi';
import { message, modal } from '@/components/AntdGlobal';
import AuthButton from '@/components/AuthButton';
import SearchForm from '@/components/SearchForm';
import { IRole } from '@/types/api';
import { IAction } from '@/types/modal';
import { formatDate } from '@/utils';

import CreateRole from './createRole';
import SetPermission from './setPermission';

const RoleList = () => {
    /* 数据管理--------------------------------------------------- */
    const [form] = Form.useForm();
    const roleRef = useRef<{
        openModal: (action: IAction, data?: IRole.RoleItem) => void;
    }>();
    const permissionRef = useRef<{
        openModal: (action: IAction, data?: IRole.RoleItem) => void;
    }>();
    const columns: ColumnsType<IRole.RoleItem> = [
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark'
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render(updateTime: string) {
                return formatDate(updateTime);
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render(createTime: string) {
                return formatDate(createTime);
            }
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render(record: IRole.RoleItem) {
                return (
                    <Space>
                        <AuthButton
                            auth="role@edit"
                            type="text"
                            onClick={() => handleEdit(record)}
                        >
                            编辑
                        </AuthButton>
                        <AuthButton
                            auth="role@setting"
                            type="text"
                            onClick={() => handleSetPermission(record)}
                        >
                            设置权限
                        </AuthButton>
                        <AuthButton
                            auth="role@delete"
                            type="text"
                            onClick={() => handleDelete(record.roleId)}
                            danger
                        >
                            删除
                        </AuthButton>
                    </Space>
                );
            }
        }
    ];
    const getTableData = (
        {
            current,
            pageSize
        }: {
            current: number;
            pageSize: number;
        },
        formData: IRole.SearchParams
    ) => {
        return rolesApi
            .getRolesList({
                ...formData,
                pageNum: current,
                pageSize
            })
            .then((res) => {
                const { data } = res;
                return {
                    total: data.page.total,
                    list: data.list
                };
            });
    };
    const { tableProps, search } = useAntdTable(getTableData, {
        form,
        defaultPageSize: 10
    });

    /* 函数定义 ---------------------------------------------------*/
    /**新增角色
     */
    const handleCreate = () => {
        roleRef.current?.openModal('create');
    };

    /**编辑角色
     * @param record
     */
    const handleEdit = (record: IRole.RoleItem) => {
        roleRef.current?.openModal('edit', record);
    };

    /**权限设置
     * @param record
     */
    const handleSetPermission = (record: IRole.RoleItem) => {
        permissionRef.current?.openModal('setting', record);
    };

    /**删除选中角色
     * @param record
     */
    const handleDelete = (roleId: string) => {
        modal.confirm({
            title: '确认',
            content: '确认删除该角色吗?',
            onOk() {
                handleSDelSubmit(roleId);
            }
        });
    };

    /**执行删除角色
     * @param roleId
     */
    const handleSDelSubmit = async (roleId: string) => {
        await rolesApi.delRole({
            roleId
        });
        message.success('删除成功');
        search.submit();
    };

    /**初始化更新角色列表
     */
    const updateRolesList = () => {
        search.reset();
    };

    return (
        <div className="role-list">
            {/* 表单 */}
            <SearchForm
                form={form}
                submit={search.submit}
                reset={search.reset}
            >
                <Form.Item
                    label="角色名称"
                    name="roleName"
                >
                    <Input />
                </Form.Item>
            </SearchForm>

            {/* table */}
            <div className="base-table">
                <div className="header-wrapper">
                    <div className="title">角色列表</div>
                    <div className="action">
                        <AuthButton
                            auth="role@create"
                            type="primary"
                            onClick={handleCreate}
                        >
                            新增
                        </AuthButton>
                    </div>
                </div>
                <Table
                    bordered
                    {...tableProps}
                    rowKey="roleId"
                    columns={columns}
                />
            </div>

            {/* 创建角色组件 */}
            <CreateRole
                mRef={roleRef}
                update={updateRolesList}
            />

            {/* 设置权限组件 */}
            <SetPermission
                mRef={permissionRef}
                update={updateRolesList}
            />
        </div>
    );
};

export default RoleList;
